package com.kay.car.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.kay.car.dao.CarDao;
import com.kay.car.dao.PriceDao;
import com.kay.car.entity.CarTable;
import com.kay.car.entity.PriceTable;
import com.kay.car.util.DataUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class CarService {
    @Autowired
    private CarDao carDao;
    @Autowired
    private PriceDao priceDao;

    private String[] tuguanL = {"1.4","1.8","2.0"};
    private String[] sangtanaL = {"1.4","1.5","1.6","1.8","2.0"};
    private String[] pasateL = {"1.4","1.8","2.0","2.8","3.0"};
    private String[] gaoerfuL = {"1.4","1.6","1.8","2.0"};
    private String[] poloL = {"1.4","1.6"};
    private String[] baolaiL = {"1.4","1.5","1.6"};
    private String[] sutengL = {"1.4","1.6","1.8","2.0"};
    private String[] maitengL = {"1.4","1.8","2.0"};
    private String[] langyiL = {"1.4","1.6","2.0"};

    public CarTable update(CarTable car){
        CarTable carTable = carDao.findOneByTitle(car.getTitle());
        if(carTable!=null){
            car.setId(carTable.getId());
            car.setUrl(carTable.getUrl());
            car.setEnable(carTable.isEnable());
            car.setDog(carTable.getDog());
        }else{
            car.setEnable(true);
        }
        car.setUpdateTime(new Date());
        return carDao.save(car);
    }

    public JSONObject getPrice(String key, String year) {
        List<CarTable> cars = carDao.findAllByYearAndKeywordLike(year, "%" + key + "%");
        Double[] prices = new Double[cars.size()];
        for (int i = 0; i < cars.size(); i++) {
            try{
                double price = Double.parseDouble(cars.get(i).getPrice().replace("¥", "").replace("万", ""));
                prices[i] = price;
            }catch (Exception e){
                System.out.println(cars.get(i).getPrice());
                e.printStackTrace();
            }
        }
        if (prices.length==0){
            return null;
        }
        return DataUtil.getPrice(prices);
    }

    public String updateUrl(Long id, String url) {
        CarTable car = carDao.findOneById(id);
        car.setUrl(url);
        carDao.save(car);
        return "ok";
    }

    public JSONArray getPriceAll(String key) {
        List<CarTable> cars = new ArrayList<>();
        if(key.equals("")){
            cars = carDao.findAll(Sort.by("id").descending());
        }else{
            cars = carDao.findAllByKeywordLike(Sort.by("id").descending(),"%" + key + "%");
        }
        HashMap<String,List<CarTable>> map = new HashMap<>();
        for (CarTable carTable:cars) {
            if(map.get(carTable.getKeyword())==null){
                map.put(carTable.getKeyword(), new ArrayList<CarTable>());
            }
            map.get(carTable.getKeyword()).add(carTable);
        }

        JSONArray arry = new JSONArray();
        for (String str :map.keySet()) {
            HashMap<String,List<CarTable>> yearMap = new HashMap<>();
            for (int i = 0; i < map.get(str).size(); i++) {
                if(yearMap.get(map.get(str).get(i).getYear())==null){
                    yearMap.put(map.get(str).get(i).getYear().replaceAll("\n",""),new ArrayList<CarTable>());
                }
                yearMap.get(map.get(str).get(i).getYear().replaceAll("\n","")).add(map.get(str).get(i));
            }


            for (String year:yearMap.keySet()) {
                HashMap<String,List<CarTable>> lMap = new HashMap<>();
                for (CarTable car :yearMap.get(year)) {
                    String l = getL(str, car.getTitle());
                    if(l.equals("")){
                        continue;
                    }

                    if(lMap.get(l)==null){
                        lMap.put(l,new ArrayList<CarTable>());
                    }
                    lMap.get(l).add(car);
                }

                for (String l :lMap.keySet()) {
                    HashMap<String,List<CarTable>> dangMap = new HashMap<>();
                    for (CarTable car:lMap.get(l)) {
                        String dang = getDang(car.getTitle());
                        if(dangMap.get(dang)==null){
                            dangMap.put(dang,new ArrayList<CarTable>());
                        }
                        dangMap.get(dang).add(car);
                    }

                    for (String dang:dangMap.keySet()) {
                        Double[] prices = new Double[dangMap.get(dang).size()];
                        for (int i = 0; i < dangMap.get(dang).size(); i++) {
                            try{
                                double price = Double.parseDouble(dangMap.get(dang).get(i).getPrice().replace("¥", "").replace("万", "").replace("\n", ""));
                                prices[i] = price;
                            }catch (Exception e){
                                System.out.println(dangMap.get(dang).get(i).getPrice());
                                e.printStackTrace();
                            }

                        }
                        if (prices.length==0){
                            continue;
                        }
                        JSONObject json = DataUtil.getPrice(prices);
                        json.put("key",str);
                        json.put("year",year);
                        json.put("l",l);
                        json.put("dang",dang);
                        json.put("time",dangMap.get(dang).get(0)==null?"":dangMap.get(dang).get(0).getUpdateTime());
                        arry.add(json);
                    }
                }
            }

//            for (String yearKey:yearMap.keySet()) {
//                double[] prices = new double[yearMap.get(yearKey).size()];
//                for (int i = 0; i < yearMap.get(yearKey).size(); i++) {
//                    try{
//                        double price = Double.parseDouble(yearMap.get(yearKey).get(i).getPrice().replace("¥", "").replace("万", "").replace("\n", ""));
//                        prices[i] = price;
//                    }catch (Exception e){
//                        System.out.println(yearMap.get(yearKey).get(i).getPrice());
//                        e.printStackTrace();
//                    }
//
//                }
//                if (prices.length==0){
//                    continue;
//                }
//                JSONObject json = DataUtil.getPrice(prices);
//                json.put("key",str);
//                json.put("year",yearKey);
//                json.put("time",yearMap.get(yearKey).get(0)==null?"":yearMap.get(yearKey).get(0).getUpdateTime());
//                arry.add(json);
//            }
        }
        arry.sort(new Comparator<Object>() {
            @Override
            public int compare(Object o1, Object o2) {
                return ((JSONObject)o2).getString("year").compareTo(((JSONObject)o1).getString("year"));
            }
        });
        arry.sort(new Comparator<Object>() {
            @Override
            public int compare(Object o1, Object o2) {
                return ((JSONObject)o2).getString("key").compareTo(((JSONObject)o1).getString("key"));
            }
        });

        return arry;
    }

//    public JSONArray getRecommend(String key) {
//        JSONArray prices = getPriceAll(key);
//        List<CarTable> cars;
//        if(key.equals("")){
//            cars = carDao.findAllByDog(2);
//        }else{
//            cars = carDao.findAllByKeywordLikeAndDog("%" + key + "%",2);
//        }
//        JSONArray recommend = new JSONArray();
//        for (CarTable carTable:cars) {
//            for (int i = 0; i < prices.size(); i++) {
//                try{
//                    if(prices.getJSONObject(i).getIntValue("count")>5){
//                        if(prices.getJSONObject(i).getString("key").equals(carTable.getKeyword())){
//                            if(prices.getJSONObject(i).getString("year").equals(carTable.getYear())){
//                                if(prices.getJSONObject(i).getString("dang").equals(getDang(carTable.getTitle()))){
//                                    if(prices.getJSONObject(i).getString("l").equals(getL(carTable.getKeyword(),carTable.getTitle()))){
//                                        float price = Float.parseFloat(carTable.getPrice().replace("¥", "").replace("万", "").replace("\n", ""));
//
//                                        System.out.println("????"+prices.getJSONObject(i).getFloatValue("price"));
//                                        System.out.println("----"+price);
//                                        System.out.println("cha"+(prices.getJSONObject(i).getFloatValue("price")-price));
//                                        float cha = prices.getJSONObject(i).getFloatValue("price") - price;
//                                        if(cha>0.3&&cha<1){
//                                            JSONObject json = new JSONObject();
//                                            json.put("info",prices.getJSONObject(i));
//                                            json.put("car",carTable);
//                                            json.put("cha",cha+"");
//                                            recommend.add(json);
//                                        }
//                                    }
//                                }
//                            }
//                        }
//                    }
//                }catch (Exception e){
//                    continue;
//                }
//            }
//        }
//
//        recommend.sort(new Comparator<Object>() {
//            @Override
//            public int compare(Object o1, Object o2) {
//                return ((JSONObject)o2).getString("cha").compareTo(((JSONObject)o1).getString("cha"));
//            }
//        });
////        JSONArray returnArray = new JSONArray();
////        for (int i = 0; i < 5; i++) {
////            returnArray.add(recommend.get(i));
////        }
//        return recommend;
//    }

    public JSONArray getRecommend(String key) {
        List<CarTable> cars;
        List<PriceTable> priceList;
        if(key.equals("")){
            cars = carDao.findAllByDog(2);
            priceList = priceDao.findAll();
        }else{
            cars = carDao.findAllByKeywordLikeAndDog("%" + key + "%",2);
            priceList = priceDao.findAllByKeywordOrderByYearDesc(key);
        }
        JSONArray recommend = new JSONArray();
        for (CarTable carTable:cars) {
            JSONObject json = new JSONObject();
            for (PriceTable priceTable:priceList) {
                if(carTable.getKeyword().replace("大众","").equals(priceTable.getKeyword())
                        &&carTable.getYear().equals(priceTable.getYear().substring(2))
                        &&carTable.getTitle().contains(priceTable.getOutput())
                        &&carTable.getTitle().contains(priceTable.getType())){
                    json.put("info",priceTable);
                }
            }
            json.put("car",carTable);
            recommend.add(json);
        }

        recommend.sort(new Comparator<Object>() {
            @Override
            public int compare(Object o1, Object o2) {
                return ((JSONObject)o2).getJSONObject("car").getString("year").compareTo(((JSONObject)o1).getJSONObject("car").getString("year"));
            }
        });
        return recommend;
    }

    public String getL(String key,String title){
        String[] lvalues;
        switch (key.replace("大众","")){
            case "途观":
                lvalues = tuguanL;
                break;
            case "宝来":
                lvalues = baolaiL;
                break;
            case "速腾":
                lvalues = sutengL;
                break;
            case "迈腾":
                lvalues = maitengL;
                break;
            case "polo":
                lvalues = poloL;
                break;
            case "高尔夫":
                lvalues = gaoerfuL;
                break;
            case "帕萨特":
                lvalues = pasateL;
                break;
            case "朗逸":
                lvalues = langyiL;
                break;
            case "桑塔纳":
                lvalues = sangtanaL;
                break;
            default:
                throw new IllegalStateException("Unexpected value: " + key);
        }
        for (String lvalue : lvalues) {
            if(title.contains(lvalue)){
                return lvalue;
            }
        }
        return "";
    }

    public String getDang(String title){
        String dang = "";
        if(title.contains("手动")){
            dang = "手动";
        }else{
            dang = "自动";
        }
        return dang;
    }

    public String enable(Long id) {
        CarTable car = carDao.findOneById(id);
        car.setDog(1);
        carDao.save(car);
        return "ok";
    }

    public String setDog(Long id, int dog) {
        CarTable car = carDao.findOneById(id);
        car.setDog(dog);
        carDao.save(car);
        return "ok";
    }
}
